package cn.xuexiluxian.open.quartz.controller;

import cn.hutool.core.util.StrUtil;
import cn.xuexiluxian.open.common.annotation.RepeatSubmit;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.xuexiluxian.open.common.annotation.Log;
import cn.xuexiluxian.open.common.controller.BaseController;
import cn.xuexiluxian.open.common.enums.BusinessType;
import cn.xuexiluxian.open.common.enums.ResultStatusCodeEnum;
import cn.xuexiluxian.open.common.response.ResponseResult;
import cn.xuexiluxian.open.quartz.entity.SystemJobLog;
import cn.xuexiluxian.open.quartz.entity.req.JobLogREQ;
import cn.xuexiluxian.open.quartz.service.SysJobLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 调度日志操作处理
 */
@RestController
@RequestMapping("task/logger")
public class SystemJobLogController extends BaseController {
    @Autowired
    private SysJobLogService sysJobLogService;

    /**
     * 查询定时任务调度日志列表
     */
    @GetMapping("page")
    @Log(title = "调度日志", businessType = BusinessType.SELECT)
    @PreAuthorize("@permission.hasPermission('task:logger:list')")
    public ResponseResult page(Page page, JobLogREQ bean) {
        page = sysJobLogService.pageList(page, bean);
        return ResponseResult.ok(page);
    }

    /**
     * 根据调度编号获取详细信息
     */
    @GetMapping(value = "get/{id}")
    @Log(title = "调度日志", businessType = BusinessType.SELECT)
    @PreAuthorize("@permission.hasPermission('task:logger:query')")
    public ResponseResult get(@PathVariable String id) {
        if(StrUtil.isBlank(id)){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        SystemJobLog systemJobLog = sysJobLogService.getById(id);
        if(systemJobLog != null) {
            return ResponseResult.ok(systemJobLog);
        }
        return ResponseResult.error(ResultStatusCodeEnum.DATA_NO_EXIST);
    }

    /**
     * 删除定时任务调度日志
     */
    @RepeatSubmit
    @PostMapping("delete")
    @Log(title = "调度日志", businessType = BusinessType.DELETE)
    @PreAuthorize("@permission.hasPermission('task:logger:delete')")
    public ResponseResult delete(@RequestBody List<String> ids) {
        if(ids == null || ids.size() <= 0){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        sysJobLogService.removeByIds(ids);
        return ResponseResult.ok();
    }

    /**
     * 清空定时任务调度日志
     */
    @RepeatSubmit
    @GetMapping("clean")
    @Log(title = "调度日志", businessType = BusinessType.CLEAN)
    @PreAuthorize("@permission.hasPermission('task:logger:clean')")
    public ResponseResult clean() {
        sysJobLogService.cleanJobLog();
        return ResponseResult.ok();
    }
}
